﻿angular.module('app')
    .controller("TaskCtrl", ['$rootScope', '$scope', 'TaskSrv', 'WorkContextSrv', 'ngTableParams', '$filter', '$timeout', '$document', 'globalConfig', 'helperSrv', '$q', '$window', 'HolidaySrv', 'UserSrv', '$stateParams', '$location', function ($rootScope, $scope, taskSrv, workContextSrv, ngTableParams, $filter, $timeout, $document, globalConfig, helperSrv, $q, $window, holidaySrv, userSrv, $stateParams, $location) {
        var currentUser = workContextSrv.getCurrentUser();
        var postUrl = 'api/topics';
        var filesList = [];
        var maxFiles = 1;
        var username = currentUser.userName;
        var defaultPageSize = 10;
        var defaultPageIndex = 0;
        var pageSize = defaultPageSize;
        var pageIndex = defaultPageIndex;
        var loadtm = null;

        $scope.taskList = {
            onLoading: false,
            stopLoading: false,
            noResult: false,
            results: [],
            firstLoad: true
        };

        $scope.taskSearch = {
            searchResult: [],
            showSearch: false,
            onSearching: false,
            query: '',
            showMessage: false
        };

        $rootScope.$broadcast("loadUserStat");
        $rootScope.$broadcast("getTaskCount", false);

        //search task function
        function searchTask() {
            $scope.taskList.onLoading = false;
            $scope.taskList.stopLoading = false;

            $scope.taskSearch.onSearching = true;
            $scope.taskSearch.showSearch = true;
            $scope.taskSearch.searchResult = [];

            //abort all previous request
            $rootScope.$broadcast("abortPendingRequest");

            taskSrv.getTasksByUser(username, $scope.taskSearch.query, 99999, 0)
                .then(function () {
                    loadtm = null;
                    Array.prototype.push.apply($scope.taskSearch.searchResult, taskSrv.tasks);
                    //$scope.taskSearch.searchResult = taskSrv.tasks;

                    $scope.taskSearch.showMessage = !data.length;
                    $scope.taskSearch.onSearching = false;
                },
                function (error) {
                    $scope.taskSearch.onSearching = false;
                }).then(function () {

                });
        }

        //reload task list when search is empty
        function reloadTaskList() {
            pageSize = defaultPageSize;
            pageIndex = defaultPageIndex;
            $scope.taskList.stopLoading = false;
            $scope.taskList.noResult = false;
            $scope.taskSearch.onSearching = false;
            $scope.taskSearch.showSearch = false;
            loadMoreTasks(true);
        }

        //watch query change
        $scope.$watch('taskSearch.query', function () {
            if (!$scope.taskList.firstLoad) {

                //if ($scope.taskSearch.query === '') {
                //    reloadTaskList();
                //} else {
                //    searchTask();
                //}
                reloadTaskList();
            }
        });

        //on search result click
        $scope.chooseTaskItem = function (sitem) {
            $scope.taskList.results = [];
            $scope.taskList.noResult = false;
            $scope.taskList.results.push(sitem);
            $scope.taskSearch.showSearch = false;
            $scope.taskSearch.onSearching = false;
        };

        //load tasks function
        function loadMoreTasks(clear) {
            //if task detail open from sketch then open task detail without loading task list
            if ($stateParams.toid != null) {
                $scope.$broadcast("viewTaskDetail");
                return;
            }
            if (clear) {
                $scope.taskList.results = [];
                pageSize = defaultPageSize;
                pageIndex = defaultPageIndex;
                $scope.taskList.onLoading = false;
                $scope.taskList.stopLoading = false;
            }

            if (!$scope.taskList.onLoading && !$scope.taskList.stopLoading) {
                $scope.taskList.onLoading = true;

                //abort all previous request
                $rootScope.$broadcast("abortPendingRequest");
                //load user stat
                $rootScope.$broadcast("loadUserStat");
                //post request get tasks
                taskSrv.getTasksByUser(username, $scope.taskSearch.query, pageSize, pageIndex++)
                    .then(function () {
                        //if there is some to load more
                        if (!$scope.taskList.stopLoading) {

                            Array.prototype.push.apply($scope.taskList.results, taskSrv.tasks);

                            if ($scope.taskList.results.length <= 0) {
                                $scope.taskList.noResult = true;
                            }

                            //if the result less than pageSize then stop loading in future
                            if (taskSrv.tasks.length < pageSize) {
                                $scope.taskList.stopLoading = true;
                            }
                        }

                        //update user stat
                        $rootScope.$broadcast("loadUserStat");

                        $scope.taskList.firstLoad = false;
                        $scope.taskList.onLoading = false;
                        loadtm = null;
                    },
                        function (error) {
                            $scope.taskList.onLoading = true;
                        }).then(function () {
                            $timeout(function () {
                                $rootScope.$broadcast('hidePreloading');
                            }, 500);
                        });
            }
        }

        //Infinity scroll
        $scope.loadMoreTasks = function () {
            $timeout(function () {
                $scope.$apply(loadMoreTasks(false));
            }, 200);
        };

        //handle reload task event
        $scope.$on("reloadTasks", function () {
            //clear task detail
            jQuery("#taskdetailiframe").empty();
            //hide task detail
            $scope.taskDetail.enabled = false;

            $scope.taskList.stopLoading = false;
            $scope.taskList.noResult = false;

            loadMoreTasks(true);
        });

        //hide search result when click to outside
        $document.bind('click', function (e) {
            if (angular.element(e.target).parents(".task-search").length === 0) {
                $scope.$apply(function () {
                    $scope.taskSearch.onSearching = false;
                    $scope.taskSearch.showSearch = false;
                });
            }
        });

        $scope.taskDetail = {
            scrollTop: 0,
            enabled: false,
            onAssigning: false,
            task: {},
            url: '',
            submitTask: {
                comment: '',
                url: '',
                path: '',
                code: '',
                attachments: [],
                onSubmitting: false,
                hasErrors: false,
                errorMessages: '',
                showError: false
            },
            assignedToMe: false,
            onLoading: false,
            onShowing: false,
        };


        //get filename from path
        var getFileNameFromPath = function (fullPath) {
            var index = fullPath.lastIndexOf("\\") + 1;
            if (index === 0) {
                index = fullPath.lastIndexOf("/") + 1;
            }
            var filename = fullPath.substr(index);

            return filename;
        };

        //validate file function
        function validateFile(fileName) {
            var validFile = true;
            //validate extension
            if (!(globalConfig.regexAllowedTaskDocumentExtension).test(fileName)) {
                alert('Only accepted file types: ' + globalConfig.allowedTaskDocumentExtension);
                validFile = false;
            }

            //validate maxFiles
            if ($scope.taskDetail.submitTask.attachments.length >= $scope.taskDetail.maxFiles) {
                alert('Max files is reached');
                validFile = false;

            }
            return validFile;
        }

        function changeFileUploadControl(e) {
            if (typeof jQuery(e) != 'undefined') {
                jQuery(e).removeClass("active-file");
                jQuery(e).addClass("has-file");
                if (typeof jQuery(e).next() != 'undefined') {
                    if (!jQuery(e).next().hasClass("has-file")) {
                        jQuery(e).next().addClass("active-file");
                    } else {
                        changeFileUploadControl(jQuery(e).next());
                    }
                }
            }
        }

        //file change function
        function fileChange() {
            var fileName = getFileNameFromPath(jQuery(this).val());
            jQuery(this).removeClass("file-error");
            if (!validateFile(fileName, 0)) {
                jQuery(this).addClass("file-error");
            } else {
                $scope.$broadcast('fileadded', { file: fileName });
                changeFileUploadControl(jQuery(this));
            }
        }

        function createUploadControl() {
            //clear old file upload control
            jQuery("#file-upload-control").html('');
            //append new file upload control
            for (var i = 0; i < $scope.taskDetail.maxFiles; i++) {
                jQuery("<input type='file' id='file-" + i + "' class='ie-file " + (i == 0 ? "active-file" : "") + "' name='files[]'>").appendTo(jQuery("#file-upload-control")).bind("change", fileChange);
            }
        }

        //open task detail redirect from sketch page
        $scope.$on("viewTaskDetail", function () {
            taskSrv.getTaskByToid($stateParams.toid).success(function (dt) {
                dt.index = -1;
                generateTaskDetail(dt);
                $timeout(function () {
                    $rootScope.$broadcast('hidePreloading');
                }, 500);
            }).error(function (dt) {
                alert(dt);
                //console.log(dt);
            });


        });

        //generate task detail page
        function generateTaskDetail(t) {
            var idx = t.index;

            $scope.taskDetail.scrollTop = t.scrollTop;

            $scope.taskDetail.enabled = true;
            $scope.taskDetail.onShowing = true;
            $scope.taskDetail.onLoading = false;

            var tmTaskSlice;
            jQuery('<i class="fa-2x fa fa-spinner fa-spin iframe-loader"></i>').appendTo(jQuery("#taskdetailiframe"));

            jQuery("<iframe src='" + t.task.uiCode + "/" + t.task.uiCode + "?toid=" + t.task.taskOid + "'></iframe>").appendTo(jQuery("#taskdetailiframe")).load(function () {
                jQuery("#taskdetailiframe").find(".iframe-loader").remove();
                if (jQuery("#iframeaction").val() !== '') {
                    $scope.$apply(function () {
                        //turn off submitting state
                        $scope.taskDetail.submitTask.onSubmitting = false;
                        $scope.taskDetail.submitTask.hasErrors = false;
                        if (jQuery("#iframeaction").val() !== '') {
                            //if current task detail is open from sketch page then reload task list
                            if ($stateParams.toid != null) {
                                $location.url("/tasks");
                                return;
                            }
                            //alert("The data got from the iframe to the app: " + jQuery("#taskdetailiframe").find("iframe").contents().find("body").html());
                            $timeout.cancel(tmTaskSlice);
                            tmTaskSlice = $timeout(function () {
                                if (jQuery("#keepTaskInList").val() === "0") {
                                    //remove task from task list
                                    if (idx > -1) {
                                        $scope.taskList.results.splice(idx, 1);
                                    }
                                }
                                //Re-update task counter
                                //$rootScope.$broadcast("getTaskCount", false);
                                $rootScope.$broadcast("decreaseTaskCount", 1);

                                //update user stat
                                $rootScope.$broadcast("loadUserStat");

                                //hide task detail
                                $scope.taskDetail.enabled = false;
                                //alert
                                jQuery("<div id='footer-notification' class='alert alert-success no-margin'><i class='fa-fw fa fa-check'></i> " + jQuery("#iframeaction").val() + " task successful</div>").appendTo(jQuery("body")).delay(3000).fadeOut();
                                //clear task detail
                                jQuery("#taskdetailiframe").empty();
                                //show 'back to list' button
                                jQuery("#taskdetailcontrol").show();
                            }, 500);
                        }
                    });
                }
                $rootScope.$broadcast('reHeight');
            });
            jQuery("#taskdetailiframe").append("<input type='hidden' id='iframeaction' value='' />");
            jQuery("#taskdetailiframe").append("<input type='hidden' id='keepTaskInList' value='0' />");
            jQuery("#taskview-iframe-loader").remove();
            jQuery("#taskdetailiframe").append('<div id="taskview-iframe-loader" class="pre-loading" style="display: none;"><i ng-class="addClass" style="color: #2C3742;;" class="fa-2x fa fa-spinner fa-spin"></i> <span class="preloadertext">Processing...</span></div>');
        }

        //handle 'open popup' event
        $scope.$on("openTaskDetail", function (e, params) {
            generateTaskDetail(params);
        });

        //handle remove task from list event
        $scope.$on("removeTaskFromList", function (e, params) {
            if (params > -1) {
                //remove task from list
                $scope.taskList.results.splice(params, 1);
                //Re-update task counter
                //$rootScope.$broadcast("getTaskCount", false);
            }
        });

        //back to list
        $scope.backToTasklist = function (t) {
            if ($stateParams.toid != null) {
                $location.url("/tasks");
                return;
            }

            //clear task detail
            jQuery("#taskdetailiframe").empty();
            //hide task detail
            $scope.taskDetail.enabled = false;
            $timeout(function () {
                angular.element($window).scrollTop(t.scrollTop);
            }, 500);
        };

        //Handle 'fileadded' event
        $scope.$on('fileadded', function (e, parameters) {
            if (helperSrv.isIe() === 9) {
                $scope.taskDetail.submitTask.attachments.push({ name: parameters.file });
            }
            else {
                $scope.taskDetail.submitTask.attachments.push(parameters.file);
            }
        });

        //remove attactment
        $scope.deleteCurrentAttachment = function (idx) {
            //remove file from reply scope
            $scope.taskDetail.submitTask.attachments = $scope.taskDetail.submitTask.attachments.filter(
            function (val) {
                return val !== this.file;
            }, this);

            //remove file from fileList array
            filesList = filesList.filter(
            function (val) {
                return val !== this.file;
            },
            this);
        };

        //Handle 'commentSubmited' event
        $scope.$on('taskSubmitted', function (e, parameters) {
            $scope.$apply(function () {
                //turn off submitting state
                $scope.taskDetail.submitTask.onSubmitting = false;
                $scope.taskDetail.submitTask.hasErrors = false;
                //var resp = parameters.data;
                //if (resp.result) {
                //    $('#createTopicBox').modal('hide');
                //    filesList = [];
                //    scope.createtopicform.$setPristine();
                //    //create new model and reset state by copy
                //    scope.newtopic = angular.copy({ /*title: '',*/ attachments: [], message: '', directTo: '' });

                //    //remove file from queue
                //    jQuery(element).find(".files").empty();
                //} else {
                //    //show error
                //    scope.hasErrorWhilePosting = true;
                //    scope.errorMessage = resp.errorMessage;
                //}
            });
        });

        //submit task
        $scope.submitTask = function (taskDetail, act) {
            //required workflow file name
            //required workflow code
            //required url
            //required path
            $scope.taskDetail.submitTask.showError = true;
            if ($scope.taskdetailform.$valid) {
                //console.log(taskDetail);
                //console.log(act);
            }
        };

        //handle model close action
        jQuery('#viewtaskdetail').on('hidden.bs.modal', function () {
            $scope.$apply(function () {
                $scope.taskDetail.onShowing = false;
                jQuery("#taskdetailiframe").html("");
                //$rootScope.$broadcast("MODAL:HIDE");

            });
        });

        //check assign status
        function checkAssigned(t) {
            return typeof t.task != 'undefined' && currentUser.userName == t.task.acceptedBy;
        }

        //check assign status
        $scope.isTaskAssignedToMe = function (t) {
            return checkAssigned(t);
        };

        //assign task to me
        $scope.assignThisTaskToMe = function (t) {
            if (!$scope.taskDetail.onAssigning) {
                //show indicator
                $scope.taskDetail.onAssigning = true;
                var operation = $scope.taskDetail.assignedToMe ? 'giveback' : 'assign';
                taskSrv.taskOperation(t.taskOid, operation, currentUser.userName).success(function (dt, st) {
                    //console.log(dt);
                    $scope.taskDetail.onAssigning = false;
                }).error(function (dt, st) {
                    //console.log(dt);
                });
            }
        };

    }])